package restaurant.selector.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import restaurant.selector.Restaurant;
import restaurant.selector.User;

public class DatabaseManager implements DatabaseWorker {
	
	private static final String DATABASE_STORE_DB = "database";
	private static final String DATABASE_STORE_FILE = "file";
	
	private static final DatabaseManager dbManager = new DatabaseManager();
	private Connection connection;
	private DatabaseWorker databaseWorker;
	
	private DatabaseManager(){
		
	}
	
	public static DatabaseManager getInstance(){
		return dbManager;
	}
	
	public void init(String driver, String username, String password, 
			String url, String storeType ){
		
		if( storeType.equals(DATABASE_STORE_DB) ){
			
			try {
				Class.forName(driver).newInstance();
				connection = DriverManager.getConnection(url, username, password);

				if( !connection.isClosed() )
					System.out.println("Database connection established");
				
				databaseWorker = new JdbcWorker(connection);
				
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		} else {
			databaseWorker = new FileWorker();
		}
		
	}
	
	public void addRestaurant(String name, boolean quick, int distance){

		databaseWorker.addRestaurant(name, quick, distance);
	}
	
	public void deleteRestaurant( Restaurant r ){
	
		databaseWorker.deleteRestaurant(r);
	}
	
	public List<Restaurant> getRestaurants(){
		
		return databaseWorker.getRestaurants();
	}
	
	public Restaurant getRestaurantByName( String name ){
		
		return databaseWorker.getRestaurantByName(name);
	}
	
	public Restaurant getRestaurantById( int id ){
		
		return databaseWorker.getRestaurantById(id);
	}
	
	public List<User> getUsers(){
		
		return databaseWorker.getUsers();
	}
	
	public User getUserByName( String name ){
		
		return databaseWorker.getUserByName(name);
	}
	
	@Override
	public void addUser(String name) {

		databaseWorker.addUser(name);
	}

	@Override
	public void deleteUser(User u) {
		
		databaseWorker.deleteUser(u);
	}

	public User getUserById( int id ){
		
		return databaseWorker.getUserById(id);
	}
}
